﻿@model Gateway.Console.Models.Deployment
@using Microsoft.Gateway.Utils
@using Microsoft.Gateway.Utils.Update

@{
    ViewBag.Title = "Update Deployment";
}

<h2>Update Service Gateway Deployment</h2>

@if (ViewBag.RdfeAuthorizationFailure)
{
    <p>
        <strong>
            An error has occurred attempting to obtain authorization for access to Microsoft Azure Management API.<br />
        </strong>
    </p>
    <p>Details:</p>
    <p class="field-validation-error">@ViewBag.AuthorizationErrorCode</p>
    <p class="field-validation-error">@ViewBag.AuthorizationErrorDescription</p>
    <br />
    <p>
        <strong>
            Before this application can deploy the Service Gateway to Microsoft Azure, it must be authorized for access to the Microsoft Azure Management API.<br />
            Click the link below to begin authorizing access.
        </strong>
    </p>
    <br />
    @Html.ActionLink("Start Authorizing Access", "Index", "Security");
}
else
{
    <div>
        <h4>Deployment</h4>
        <hr />
        <dl class="dl-horizontal">
            <dt>
                @Html.DisplayNameFor(model => model.ServiceName)
            </dt>
            <dd>
                @Html.DisplayFor(model => model.ServiceName)
            </dd>
            <dt>
                @Html.DisplayNameFor(model => model.RegionSelection)
            </dt>
            <dd>
                @Html.DisplayFor(model => model.RegionSelection)
            </dd>
            <dt>
                @Html.DisplayNameFor(model => model.InstanceCount)
            </dt>
            <dd>
                @Html.DisplayFor(model => model.InstanceCount)
            </dd>
            <dt>
                @Html.DisplayNameFor(model => model.SubscriptionSelection)
            </dt>
            <dd>
                @Html.DisplayFor(model => model.SubscriptionSelection)
            </dd>
            <dt>
                @Html.DisplayNameFor(model => model.DeployedVersion)
            </dt>
            <dd>
                @Html.DisplayFor(model => model.DeployedVersion)
            </dd>
        </dl>
        <hr />
        <h4>Available Updates</h4>
        <table class="table">
            <tr>
                <th>

                </th>
                <th>
                    Version
                </th>
                <th>
                    Severity
                </th>
                <th>
                    Description
                </th>
            </tr>

            @foreach (var update in ViewBag.AvailableUpdates)
            {
                string rowClass = "info";
                switch ((UpdateSeverity)update.Severity)
                {
                    case UpdateSeverity.Critical:
                        rowClass = "danger";
                        break;

                    case UpdateSeverity.Important:
                        rowClass = "warning";
                        break;
                }
                <tr class="@rowClass">
                    <td>
                        <a class="applyLink" href="#" onclick="applyUpdate('@VersionUtils.GatewayFormat(update.Version)', false)">Apply Update</a>
                    </td>
                    <td>
                        @VersionUtils.GatewayFormat(update.Version)
                    </td>
                    <td>
                        @update.Severity
                    </td>
                    <td>
                        @Html.Raw(update.Description)
                    </td>
                </tr>
            }
        </table>
        <hr />
        <h4>Previous Versions</h4>
        <table class="table">
            <tr>
                <th>

                </th>
                <th>
                    Version
                </th>
                <th>
                    Severity
                </th>
                <th>
                    Description
                </th>
            </tr>

            @foreach (var update in ViewBag.PreviousUpdates)
            {
                <tr>
                    <td>
                        <a class="applyLink" href="#" onclick="applyUpdate('@VersionUtils.GatewayFormat(update.Version)', @(update.Version < VersionUtils.ParseVersion(Model.DeployedVersion) ? "true" : "false"))">Apply Update</a>
                    </td>
                    <td>
                        @VersionUtils.GatewayFormat(update.Version)
                    </td>
                    <td>
                        @update.Severity
                    </td>
                    <td>
                        @Html.Raw(update.Description)
                    </td>
                </tr>
            }
        </table>
        <div class="form-actions no-color">
            @Html.ActionLink("Back to List", "Index")
        </div>
        <br />
        <br />
        <div id="progressBarContainer" style="width:280px;display:none">
            <div class="progress progress-striped active">
                <div id="progressBar" class="progress-bar" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
                    <span class="sr-only"></span>
                </div>
            </div>
        </div>
        <div id="deploymentStatus">

        </div>
    </div>
}
@section Scripts {
    <script type="text/javascript">

        var statusTimer;
        var operationInProgress = @(Model.OperationInProgress ? "true" : "false");

        $(document).ready(function () {
            if (operationInProgress) {
                $("#progressBarContainer").show();
                $('#deploymentStatus').empty();
                $('#deploymentStatus').css('color', 'black');
                $('.applyLink').addClass('disabled');
                statusTimer = setInterval(function () { displayStatus() }, 3000);
            }
        });

        function applyUpdate(version, downgrade) {
            if (operationInProgress) {
                return false;
            }
            var confirmMessage = 'You are about to migrate this Gateway deployment to version: ' + version + '.';
            if (downgrade) {
                confirmMessage = confirmMessage + '\n\nNOTE: This is a version downgrade.';
            }
            if (confirm(confirmMessage + '\n\nThis operation may not be able to be undone.\n\nAre you sure you want to continue?')) {
                operationInProgress = true;
                $("#progressBarContainer").show();
                $('#deploymentStatus').empty();
                $('#deploymentStatus').css('color', 'black');
                $('.applyLink').addClass('disabled');

                $.ajax({
                    type: "POST",
                    url: '@Url.Action("UpdateVersion")',
                    data: { id : @(Model.DeploymentId), version: version},
                    error: function (xhr, status, error) {
                        $("#progressBar").addClass("progress-bar-danger");
                        $('#deploymentStatus').css('color', 'red');
                        $('#deploymentStatus').append(error);
                    },
                    success: function () {
                        statusTimer = setInterval(function () { displayStatus() }, 3000);
                    }
                });
            }
            return false;
        }

        function displayStatus() {

            $.ajax({
                type: "GET",
                url: '@Url.Action("GetDeploymentStatus")',
                cache: false,
                data: { deploymentId: @(Model.DeploymentId) },
                error: function (xhr, status, error) {
                    $('#deploymentStatus').css('color', 'red');
                    $('#deploymentStatus').append(error);
                    clearInterval(statusTimer);
                },
                success: function (data) {
                    $('#deploymentStatus').empty();
                    $.each(data, function (idx) {
                        $('#deploymentStatus').append("<div>" + data[idx].Message + "</div>");

                        if (data[idx].Success == false) {
                            $("#progressBarContainer").hide();
                            $('#deploymentStatus').css('color', 'red');
                        }

                        if (data[idx].Message.search("Finished Deployment") >= 0) {
                            window.location.href = '@Url.Action("Index")';
                        }
                    });
                }
            });
        }

    </script>
}
